package com.lovo.project.servlet.RolePermission;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lovo.project.enums.ProductEnum;
import com.lovo.project.exception.OurException;
import com.lovo.project.service.RolePermissionService;
import com.lovo.project.service.impl.RolePermissionServiceImpl;
import com.lovo.project.vo.ResultVO;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @title 角色权限添加url
 * @author: chenqiang
 * @date: 2020/11/4 16:20
 */
@WebServlet(name = "RolePermissionServlet",value = "/RolePermission/rolePermission")
public class RolePermissionServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        RolePermissionService service=new RolePermissionServiceImpl();
        int roleId=Integer.parseInt(request.getParameter("roleId"));
        String permissionIdAddArray = request.getParameter("permissionIdArray");

        PrintWriter out = response.getWriter();
        try {
            ObjectMapper mapper = new ObjectMapper();
            List list = mapper.readValue(permissionIdAddArray, List.class);
            System.out.println(list.size());
            if(list.size() != 0){
                service.deletePermissionByRoleIdAndPermissionIdList(roleId);
                service.addPermissionByRoleIdAndPermissionIdList(roleId,list);
            }else{
                service.deletePermissionByRoleIdAndPermissionIdList(roleId);
            }
            out.print(ResultVO.success().toJson());
        } catch (OurException e) {
            out.print(ResultVO.fail(e.getCodeEnum()).toJson());
        }catch (Exception e1){
            out.print(ResultVO.fail(ProductEnum.PRODUCT_Update_ENUM).toJson());
        }finally {

            out.close();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      doPost(request,response);
    }
}
